package com.hd.binlog.core;

import com.hd.binlog.config.MySqlHostProfile;
import com.hd.binlog.listen.IMysqlDataListener;
import com.hd.binlog.thread.BinlogThreadStarter;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhanghaidong
 * @version v1.0
 * @description
 * @date 2019/9/24
 */
@Component
public class BinLogBeanProcessor implements SmartInitializingSingleton {
    private ApplicationContext context;

    @Autowired
    private MySqlHostProfile profile;

    public BinLogBeanProcessor(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public void afterSingletonsInstantiated() {
        Map<String, IMysqlDataListener> beans = context.getBeansOfType(IMysqlDataListener.class);

        Map<String, List<MysqlDataListenerData>> listeners = beans.values().stream()
                .map(MysqlDataListenerData::new)
                .collect(Collectors.groupingBy(MysqlDataListenerData::getHostName));

        listeners.forEach((k, v) -> new BinlogThreadStarter().runThread(profile.getByNameAndThrow(k), v));
    }
}
